<?php

namespace app\admin\controller;

use app\admin\library\Excel;
use app\common\controller\Backend;
use think\facade\Db;
use think\db\exception\PDOException;
use think\exception\ValidateException;


/**
 * 年检记录  
 *
 */
class XPotcheck extends Backend
{
    /**
     * XPotcheck模型对象
     * @var \app\admin\model\XPotcheck
     */
    protected $model = null;
    
    protected $quickSearchField = ['NJNO'];

    protected $defaultSortField = 'NJNO,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XPotcheck;
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $TCNO=$this->request->get('TCNO');
        if($TCNO){
            $wheres['TCNO']=$TCNO;
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        foreach ($res as $re) {
            $sql="select max(x_insurance.enddate) as bx from x_insurance,x_insurancepot where x_insurance.policyno=x_insurancepot.policyno and x_insurancepot.tcno='$re[TCNO]'";
            $re['bx']=\think\facade\Db::query($sql)[0]['bx'];
//            $re['CHECKDATE']=date('Y-m-d',strtotime( $re['CHECKDATE']));
//            $re['bx']=$this->model->yxq($re['TCNO']);
        }
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }



    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['NJNO']='NJ'. $this->microtime_format('YmdHisx',$this->microtime_float());
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $data['UPLOADER']=$adminInfo['nickname'];
            $data['UPLOADTIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 导出
     */
    public function out(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $TCNO=$this->request->get('TCNO');
        if($TCNO){
            $wheres['TCNO']=$TCNO;
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $data = $this->model
            ->field(['TCNO','CHECKDATE','CHECKTYPE','NEXTCHECKDATE','NEXTCHECKTYPE'])
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->select()   ->toArray();

        $head=['箱号','年检日期','年检类型','下次年检日期','下次年检类型'];
        $key=['TCNO','CHECKDATE','CHECKTYPE','NEXTCHECKDATE','NEXTCHECKTYPE'];
//        foreach ($data as &$v) {
//            $v=array_values($v);
//        }
        // 调用类库，读取excel中的内容
//        $a=Excel::export($head,'',$data,'对账单导出');

        Excel::downloadExcel('年检导出',$data,$head,$key);

    }

}